#!/usr/bin/env python
#!conding:utf-8
"""
author:Johnson
date: 2017/5/24 10:29
version: v1.0
description:
    工具类和方法
"""



## 将对象使用json序列化并转换成前台可以识别的方式
import functools
import json
from flask.helpers import url_for
from flask_login.utils import current_user
from flask.json import jsonify
from werkzeug.utils import redirect
from blog import app, db
from blog.model import get_all


def response_data(keyTuple,list):
    """
    将字典对象转换为前端可以识别的json对象，前端ajax调用时使用
    :param keyTuple key值tuple
    :param list     内容列表
    :return:
    """
    ret = []
    for item in list:
        dicts = dict(zip(keyTuple,item))
        ret.append(dicts)
    app.logger.debug('返回数据为--->{}'.format(ret))
    return jsonify(json.dumps(ret))



def transaction(func):
    """
    执行完成函数后事物提交
    """
    @functools.wraps(func)
    def warpper(*args,**kwargs):
        ret = func(*args,**kwargs)
        db.session.commit()
        return ret
    return warpper

def check_permission(permission):
    """
    后端功能的权限检查
    """
    def decorator(func):
        @functools.wraps(func)
        def warpper(*args,**kwargs):
            sql = "SELECT t1.permission_id AS permission_id FROM t_role_permission t1 JOIN t_user_role t2 ON t2.role_id = t1.role_id WHERE t2.user_id = :user_id"
            params = {
                    "user_id":current_user.id
            }
            list = get_all(sql,params)
            if (permission,) in list:
                return func(*args,**kwargs)
            else:
                return redirect(url_for('auth_view.unauthorized'))
        return warpper
    return decorator




